import 'dart:async';

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:matuo/page/tool/QrPage.dart';
import 'package:matuo/utils/DIYColors.dart';

import '../ble/BluetoothStateUtil.dart';
import '../route/RouteUtils.dart';
import '../route/Routes.dart';
import '../utils/Utils.dart';
import 'navigation_bar_item.dart';

//首页导航栏组建（底部和顶部）
class NavigationBarWidget extends StatefulWidget {
  NavigationBarWidget(
      {super.key,
      required this.tabColors,
      required this.tabItems,
      required this.tabLabels,
      required this.tabIcons,
      required this.tabActiveIcons,
      this.currentIndex = 0,
      this.themeData,
      this.onItemChange,
      this.bottomNavigationBarType,
      this.bottomBarIconWidth,
      this.bottomBarIconHeight}) {
    // assert(tabItems.length != tabLabels.length && tabItems.length!= tabIcons.length&& tabItems
    //     .length!= tabActiveIcon.length);
    if (tabItems.length != tabLabels.length &&
        tabItems.length != tabIcons.length &&
        tabItems.length != tabActiveIcons.length) {
      throw Exception(
          "tabItems、tabLabels、tabIcons、tabActiveIcon length must same！ ");
    }
  }

  final List<Color> tabColors;

  //界面集合
  final List<Widget> tabItems;

  //标题集合
  final List<String> tabLabels;

  //未选中icon
  final List<String> tabIcons;

  //选中icon
  final List<String> tabActiveIcons;

  //当前页面下标
  int currentIndex = 0;

  //底部导航栏切换事件
  final ValueChanged<int>? onItemChange;

  //页面主题
  final ThemeData? themeData;

  //底部导航栏风格
  final BottomNavigationBarType? bottomNavigationBarType;

  //底部导航栏icon宽高
  final double? bottomBarIconWidth;
  final double? bottomBarIconHeight;

  @override
  State<StatefulWidget> createState() {
    return _NavigationBarWidgetState();
  }
}

class _NavigationBarWidgetState extends State<NavigationBarWidget> {
  @override
  void initState() {
    super.initState();
    //第一次进入默认调用一次
    // widget.onItemChange?.call(widget.currentIndex);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: widget.tabColors[widget.currentIndex],
        //tab页面
        appBar: _appBar(),
        body:
            IndexedStack(index: widget.currentIndex, children: widget.tabItems),
        //底部导航栏
        bottomNavigationBar: Theme(
          data: widget.themeData ??
              Theme.of(context).copyWith(
                splashColor: Colors.transparent,
                highlightColor: Colors.transparent,
              ),
          child: BottomNavigationBar(
              unselectedItemColor: Colors.black,
              selectedItemColor: Colors.orange,
              backgroundColor: DIYColors.gray_f4,
              type: widget.bottomNavigationBarType ??
                  BottomNavigationBarType.fixed,
              currentIndex: widget.currentIndex,
              onTap: (index) {
                //重复事件不处理
                if (widget.currentIndex == index) {
                  return;
                }
                //点击切换page事件
                widget.onItemChange?.call(index);
                widget.currentIndex = index;
                setState(() {});
              },
              items: _barItemList()),
        ));
  }

  ///底部导航栏集合
  List<BottomNavigationBarItem> _barItemList() {
    List<BottomNavigationBarItem> items = [];
    for (var i = 0; i < widget.tabItems.length; i++) {
      items.add(BottomNavigationBarItem(
        activeIcon: NavigationBarItem(
          builder: (_) => Image.asset(
            widget.tabActiveIcons[i],
            width: widget.bottomBarIconWidth ?? 32.w,
            height: widget.bottomBarIconHeight ?? 32.w,
          ),
        ),
        icon: Image.asset(
          widget.tabIcons[i],
          width: widget.bottomBarIconWidth ?? 32.w,
          height: widget.bottomBarIconHeight ?? 32.w,
        ),
        label: widget.tabLabels[i],
      ));
    }
    return items;
  }

  // 头部标题
  AppBar _appBar() {
    return AppBar(
      backgroundColor: Colors.transparent,
      systemOverlayStyle: const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.dark,
        systemNavigationBarColor: Colors.white,
        systemNavigationBarDividerColor: Colors.transparent,
        systemNavigationBarIconBrightness: Brightness.dark,
      ),
      title: Container(
        margin: EdgeInsets.only(left: 15.r, right: 15.r, top: 15.r),
        child: Row(
          children: [
            Text(
              widget.tabLabels[widget.currentIndex],
              style: TextStyle(
                  color: Colors.black,
                  fontSize: 20.sp,
                  fontWeight: FontWeight.bold),
            ),
            const Expanded(child: SizedBox()),
            GestureDetector(
              onTap: () {
                _show();
              },
              child: Image.asset(
                  Utils.instance.getImagePathPNG("icon_more_fun"),
                  width: 30.w,
                  height: 30.w,
                  fit: BoxFit.fill),
            )
          ],
        ),
      ),
    );
  }

  //弹出menu
  void _show() {
    BluetoothStateUtil.instance.bluetoothStateCallback();
    showMenu(
        context: context,
        color: Colors.white,
        shadowColor: Colors.white,
        surfaceTintColor: Colors.white,
        position: RelativeRect.fromDirectional(
            textDirection: TextDirection.rtl,
            start: 0,
            top: 90,
            end: 100,
            bottom: 100),
        constraints: BoxConstraints(maxWidth: 100.w, maxHeight: 200.w),
        items: List.generate(
            4,
            (index) => PopupMenuItem(
                  child: Container(
                      padding: EdgeInsets.only(left: 5.r),
                      width: 100,
                      height: 44,
                      alignment: AlignmentDirectional.center,
                      child: Row(children: [
                        Image.asset(
                            Utils.instance.getImagePathPNG("icon_more_fun"),
                            width: 15.w,
                            height: 15.w,
                            fit: BoxFit.fill),
                        SizedBox(width: 10.r),
                        Text(
                          widget.tabLabels[index],
                          style: TextStyle(fontSize: 15.sp),
                        )
                      ])),
                  onTap: () {
                    if (BluetoothStateUtil.instance.getBluetoothState()) {
                      if (index == 0) {
                        showQrPage();
                      } else {
                        RouteUtils.pushForNamed(context, RoutePath.scan);
                      }
                    } else {
                      BluetoothStateUtil.instance.turnOn();
                    }
                  },
                )));
  }

  //跳转扫码页面
  Future<void> showQrPage() async {
    final cameras = await availableCameras();
    final firstCamera = cameras.first;
    RouteUtils.push(
        context,
        QrPage(
          camera: firstCamera,
        ));
  }
}
